package com.rio.dandan.shiro;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.rio.dandan.dao.UserAccountDao;
import com.rio.dandan.pojo.UserAccount;

public class RpcRealm extends AuthorizingRealm {

    @Resource
    private UserAccountDao userAccountDao;

    /**
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 权限认证
        System.out.println("===============" + principals);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> permissions = new HashSet<String>();
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 账户认证
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        SimpleAuthenticationInfo info = null;
        UserAccount userAccount = userAccountDao.getUserAccountByAccount(username);
        if (userAccount != null) {
            String uid = userAccount.getUid();
            String password = userAccount.getPassword();
            String salt = userAccount.getSalt();
            info = new SimpleAuthenticationInfo(uid, password.toCharArray(), getName());
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }
        return info;
    }

}
